import pymongo
import re
import jieba
myclient = pymongo.MongoClient("mongodb://82.157.127.245:27999/")
#myclient = pymongo.MongoClient("mongodb://127.0.0.1:27999/")
mydb = myclient["weibo"]
mycollection = mydb["index2"]


def get_doc_by_regex(query):
    items = []
    index = []
    pos = query.find("*")
    if pos == 0:
        # 通配符在开头
        print("通配符在开头")
        query = query.replace("*", "")
        myquery = {"item": {"$regex": "{}$".format(query)}}

    elif pos == len(query) - 1:
        # 通配符在结尾
        print("通配符在结尾")
        query = query.replace("*", "")
        myquery = {"item": re.compile(query)}
    else:
        # 通配符在中间
        query = query.split("*")
        myquery = {"item": {"$regex": "^{}.*{}$".format(query[0], query[1])}}

    mydocs = mycollection.find(myquery)
    if mydocs is not None:
        for doc in mydocs:
            items.append(doc.get("item"))
            index_list = doc.get("index")
            for idx in index_list:
                index.append(idx[0])

    return items, index


def insert_into_index(item, index):
    mycollection.insert_one({"item":item, "index": index})

def save_doc_num(num):
    myquery = {"num": "doc_num"}
    mydoc = mycollection.find_one(myquery)
    if mydoc is None:
        mycollection.insert_one({"num": "doc_num", "num_value": num})
    else:
        mycollection.delete_one(myquery)
        mycollection.insert_one({"num": "doc_num", "num_value": num})
def get_doc_num():
    myquery = {"num": "doc_num"}
    mydoc = mycollection.find_one(myquery)
    if mydoc is None:
        return 0
    return mydoc.get("num_value")

def get_item(query):

    items = []
    myquery = {"item": re.compile(query)}
    docs = mycollection.find(myquery).limit(10)
    for doc in docs:
        items.append({"item_title" : doc.get("item")})
    return items

def get_suggestion_item(query):
    items = []
    myquery = {"item": {"$regex":"^{}.*".format(query)}}
    docs = mycollection.find(myquery).limit(10)
    for doc in docs:
        items.append(doc.get("item"))
    return items

def find_by_item(item):
    myquery = {"item": item}
    mydoc = mycollection.find_one(myquery)
    return mydoc

def update_by_item(item, index):
    myquery = {"item": item}
    mycollection.delete_one(myquery)
    insert_into_index(item, index)

if __name__ == "__main__":
    items, index = get_doc_by_regex("*研究所")
    print(len(items))
    #find_by_item("祝贺")
    #print(get_doc_num())
    # seg_list = jieba.cut("中国科学院怎么样")
    # query_item = []
    # for seg in seg_list:
    #     print(seg)
    # print(get_suggestion_item("中国"))
    # save_doc_num(50)
    # save_doc_num(100)
    # save_doc_num(150)
    # save_doc_num(200)
    # print(get_doc_num())